package cn.etynit.service.impl;

import cn.etynit.domain.ExpenseTapWater;
import cn.etynit.dto.RechargeDto;
import cn.etynit.exception.GlobalException;
import cn.etynit.exception.GlobalExceptionCodeEnum;
import cn.etynit.mapper.ExpenseTapWaterMapper;
import cn.etynit.result.JsonResult;
import cn.etynit.service.IExpenseTapWaterService;
import cn.etynit.util.AssertUtil;
import cn.etynit.vo.Logininfo;
import cn.etynit.vo.RechargeVo;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author etyn
 * @since 2022-12-08
 */
@Service
public class ExpenseTapWaterServiceImpl extends ServiceImpl<ExpenseTapWaterMapper, ExpenseTapWater> implements IExpenseTapWaterService {

    private static final String WATER_RATE_RECHARGED_SUCCESSFULLY = "水费充值成功！";

    @Override
    public JsonResult recharge(RechargeVo rechargeVo) {
        Long userId = rechargeVo.getUserId();
        BigDecimal money = rechargeVo.getMoney();
        int i = money.compareTo(BigDecimal.ZERO);
        if (i == 0 || i < 0){
            throw new GlobalException(GlobalExceptionCodeEnum.ERROR);
        }
        Wrapper<ExpenseTapWater> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id",userId);
        ExpenseTapWater expenseTapWater = selectOne(wrapper);
        if (expenseTapWater == null){
            throw new GlobalException(GlobalExceptionCodeEnum.ERROR);
        }
        expenseTapWater.setResidue(money);
        updateById(expenseTapWater);
        return JsonResult.success(WATER_RATE_RECHARGED_SUCCESSFULLY);
    }

    /**
     * 根据用户id查账单
     * @param userId
     * @return
     */
    @Override
    public ExpenseTapWater selectByUserId(Long userId) {
        Wrapper<ExpenseTapWater> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id",userId);
        return selectOne(wrapper);
    }
}
